package com.helloandroid.activitys

import android.animation.ValueAnimator
import android.os.Debug
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.activity.viewModels
import com.business.Analyse
import com.business.AnalyseKey
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.R
import com.helloandroid.ads.SmallNativeAdUtil
import com.helloandroid.ads.VideoAdUtil
import com.helloandroid.base.BaseActivity
import com.helloandroid.dialogs.AwardDialog
import com.helloandroid.models.butie.HeShuiViewModel
import com.helloandroid.tools.AppConfig
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.MyTimeUtils
import com.helloandroid.tools.MyTimeUtils.format_hhmm
import com.helloandroid.tools.MyTimeUtils.getOffsetTimeMs
import com.helloandroid.tools.MyTimeUtils.getStartDayMs
import com.helloandroid.tools.NetWorkUtil
import com.helloandroid.view.HeShuiProgress
import com.helloandroid.view.XView
import com.helloandroid.vo.HeShuiInfo
import java.util.*

class HSItem(var id: Int, var startOffset: Long, var endOffset: Long, var desc: String, var bitmapRes: Int = 0) {
    val timeSegStr: String
        get() {
            val sb = StringBuilder()
            sb.append(format_hhmm(startOffset))
            sb.append("-")
            sb.append(format_hhmm(endOffset))
            return sb.toString()
        }
}


class HeShuiDaKaActivity : BaseActivity() {

    companion object {
        val dataLst: ArrayList<HSItem> = arrayListOf<HSItem>()

        init {
            // 第1杯
            dataLst.add(HSItem(1, getOffsetTimeMs(8, 0),
                    getOffsetTimeMs(8, 45),
                    "清理肠胃.经过一晚的消耗,起床时身体正处于缺水状态,这时也是肾脏解毒的时间段,喝杯水有利于清理肠胃、排除身体毒素,促进身体恢复正常的新陈代谢."))

            // 第2杯
            dataLst.add(HSItem(2,
                    getOffsetTimeMs(9, 0),
                    getOffsetTimeMs(11, 15),
                    "提高活力.刚开始一天的工作，喝一杯水有利于让人充满活力,提高工作效率.同时这是肠胃排毒的时间段,可以帮助排除体内毒素."))

            // 第3杯
            dataLst.add(HSItem(3,
                    getOffsetTimeMs(11, 30),
                    getOffsetTimeMs(13, 15),
                    "增加饱腹.经过一上午的工作，在午餐之前可以喝一杯水,增加饱腹感,避免吃中餐时进食太多,同时这也是心脏排毒的时间段,可以帮助排除体内毒素."))

            // 第4杯
            dataLst.add(HSItem(4,
                    getOffsetTimeMs(13, 30),
                    getOffsetTimeMs(14, 45),
                    "促进消化.午餐很重要,但是也要适量的吃到八分饱,如果吃得太饱会给肠胃造成负担,所以要记得在饭后20分钟喝杯水,促进消化."))

            // 第5杯
            dataLst.add(HSItem(5,
                    getOffsetTimeMs(15, 0),
                    getOffsetTimeMs(17, 15),
                    "促进消化.午餐很重要,但是也要适量的吃到八分饱,如果吃得太饱会给肠胃造成负担,所以要记得在饭后20分钟喝杯水,促进消化."))

            // 第6杯
            dataLst.add(HSItem(6,
                    getOffsetTimeMs(17, 30),
                    getOffsetTimeMs(18, 45),
                    "减少疲劳饥饿.一天的工作结束了,身体比较疲惫劳累,下班之前记得喝杯温开水,缓解因为工作带来的疲劳哦."))

            // 第7杯
            dataLst.add(HSItem(7,
                    getOffsetTimeMs(19, 0),
                    getOffsetTimeMs(20, 15),
                    "促进血液循环和排毒.这时正是身体新陈代谢最旺盛的时间段,可以通过补充水分来促进血液循环和身体排毒."))

            // 第8杯
            dataLst.add(HSItem(8,
                    getOffsetTimeMs(20, 30),
                    getOffsetTimeMs(21, 15),
                    "调节血液浓度.睡前这个时间之内喝杯水,可以调节血液浓度,防止血液粘稠,补充睡眠时因出汗而失去的水分.另外，建议大家睡前几分钟内不要喝水,避免第二天水肿."))

        }
    }

    // views
    lateinit var tvTitle: TextView
    lateinit var tvTime: TextView
    lateinit var tvDesc: TextView
    lateinit var btnDaka: Button
    lateinit var hsProgress: HeShuiProgress
    lateinit var xView:XView

    var isReady = false
    var dstItem: HSItem? = null
    var mInfo : HeShuiInfo? = null
    val model:HeShuiViewModel by viewModels()

    override fun getContentViewResId() = R.layout.activity_heshuidaka

    override fun initView() {
        // init views
        tvTitle = findViewById(R.id.tvTitle)
        tvTime = findViewById(R.id.tvTime)
        tvDesc = findViewById(R.id.tvDesc)
        btnDaka = findViewById(R.id.btnDaka)
        hsProgress = findViewById(R.id.hsProgress)
        xView = findViewById(R.id.xView)
        xView.drawHeight = 0f
        hsProgress.setSelectedListener(object : HeShuiProgress.ISelected {
            override fun selected(idx: Int) {
                if (!isReady) {
                    return
                }
                updateUIByIdx(idx)
                hsProgress.invalidate()
            }
        })

        // back
        findBtn(R.id.ibBack).setOnClickListener { finish() }

        btnDaka.setOnClickListener { daka() }

        SmallNativeAdUtil.showNativeAd(this,findViewById(R.id.nativeView))
    }

    override fun initData() {
        model.getInfo { success, info->
            isReady = success
            if (isReady){
                mInfo = info
                dstItem = null
                initUI()
            }
        }

        if (AppConfig.isDebug) {
            Log.e("Mem", "========= 喝水打卡=显示内存=========")
            Log.e("Mem", "getNativeHeapAllocatedSize mem:" + Debug.getNativeHeapAllocatedSize() / 1024 / 1024 + "M")
            Log.e("Mem", "getNativeHeapFreeSize mem:" + Debug.getNativeHeapFreeSize() / 1024 / 1024 + "M")
            Log.e("Mem", "getNativeHeapSize mem:" + Debug.getNativeHeapSize() / 1024 / 1024 + "M")
        }
    }
    private fun daka(){
        if (!isReady || dstItem == null) {
            return
        }
        if (!NetWorkUtil.networkConnected()){
            AppUtil.toast("请打开网络!")
            return
        }

        if (xView.state == XView.State.DakaIng){
            return
        }

        // 判断是打卡还是补卡
        val todayTimeMs = MyTimeUtils.getTodayOffsetMs(AppUtil.sysTime)
        if (todayTimeMs in dstItem!!.startOffset..dstItem!!.endOffset){
            // 正常打卡
            Analyse.report(AnalyseKey.HeShui_Daka)
            successDaka()
        }else{
            // 补卡
            VideoAdUtil.playVideoAd(this){success->
                if (success){
                    Analyse.report(AnalyseKey.HeShui_Daka_Video)
                    successDaka()
                }
            }
        }
    }

    private fun successDaka(){
        val tmpItem = dstItem!!
        val awardCoin = 48
        AppUtil.appViewModel().heShuiDaKa(tmpItem.id, awardCoin)
        mInfo?.setValueByHeShuiId(tmpItem.id, 1)

        // 更新UI
        val selectedIdx = tmpItem.id - 1
        updateUIByIdx(selectedIdx)
        updateHSProgress(selectedIdx)

        playXViewAnim()

        // 一个延迟后显示对话框
        model.delayExecute(1800L){
            val dialog = AwardDialog(this,awardCoin)
            dialog.reasonKey = AnalyseKey.HeShui_Daka_Double
            dialog.show()
        }
    }

    /**
     * 注意:  idx是从0开始的
     */
    fun updateUIByIdx(idx: Int) {
        val info = mInfo!!
        var hsItem = dataLst[idx]
        tvTitle.text = "第${hsItem.id}杯水"
        tvTime.text = hsItem.timeSegStr
        tvDesc.text = hsItem.desc
        val stateArr = info.stateArr
        if (stateArr[hsItem.id - 1] > 0) {
            // 已经打卡
            btnDaka.setBackgroundResource(R.drawable.dd_btn_gray)
            btnDaka.text = "已经打卡"
            dstItem = null
            xView.state = XView.State.AlreadyDaKa
        } else {
            xView.state = XView.State.NotDaka
            // 还没有打卡
            // 1. 可能时间还没到
            // 2. 可能时间到了,但是还没打卡
            // 3. 错过了时间,补卡
            val sysTime = AppUtil.sysTime
            val offsetTodayMs = MyTimeUtils.getTodayOffsetMs(sysTime)
            if(offsetTodayMs < hsItem.startOffset){
                // case 1
                btnDaka.setBackgroundResource(R.drawable.dd_btn_gray)
                btnDaka.text = "时间还没到"
                dstItem = null
            }else if(offsetTodayMs > hsItem.endOffset){
                // case 3
                dstItem = hsItem
                btnDaka.setBackgroundResource(R.drawable.btn_red)
                btnDaka.text = "第${hsItem.id}杯 补卡"
            }else{
                // case 2
                dstItem = hsItem
                btnDaka.setBackgroundResource(R.drawable.btn_blue)
                btnDaka.text = "第${hsItem.id}杯打卡"
            }
        }
    }

    private fun initUI() {
        val sysTime = AppUtil.sysTime
        var hsItem = getHsItem(sysTime)
        var selectedIdx: Int
        if(hsItem != null){
            selectedIdx = hsItem.id - 1
        }else{
            hsItem = getNestestHsItem(sysTime)
            selectedIdx = if(hsItem != null){
                hsItem.id - 1
            }else{
                dataLst.size - 1
            }
        }
        updateUIByIdx(selectedIdx)
        updateHSProgress(selectedIdx)
    }

    private fun updateHSProgress(selectedIdx: Int){

        // 计算下面需要的状态
        val stateArr = mInfo!!.stateArr
        val timeMsOffset = MyTimeUtils.getTodayOffsetMs(AppUtil.sysTime)
        val iconStateArr = IntArray(HeShuiProgress.ICON_COUNT)
        for (i in 1..iconStateArr.size) {
            if (stateArr[i - 1] > 0) {
                // 已喝水
                iconStateArr[i - 1] = HeShuiProgress.COMPLETED
            } else {
                // 没有喝 或者 还没解锁
                val tmpItem = dataLst[i - 1];
                if (timeMsOffset < tmpItem.startOffset) {
                    // 锁住了
                    iconStateArr[i - 1] = HeShuiProgress.LOCKED
                } else {
                    // 还没有喝
                    iconStateArr[i - 1] = HeShuiProgress.UNCOMPLETE
                }
            }
        }

        // 还要判断当前是否处于可以领取的时间段
        val hsItem = getHsItem(AppUtil.sysTime)
        if (hsItem != null){
            // 判断是否已经领取
            if (iconStateArr[hsItem.id - 1] == HeShuiProgress.UNCOMPLETE){
                iconStateArr[hsItem.id - 1] = HeShuiProgress.CURRENT_ENABLE
            }
        }

        hsProgress.refresh(iconStateArr, selectedIdx)
    }

    private fun getHsItem(time: Long): HSItem? {
        val dayStartMs = getStartDayMs(time)
        for (hsItem in dataLst) {
            if (time >= dayStartMs + hsItem.startOffset &&
                    time <= dayStartMs + hsItem.endOffset) {
                return hsItem
            }
        }
        return null
    }

    private fun getNestestHsItem(time: Long): HSItem? {
        val dayStartMs = getStartDayMs(time)
        for (hsItem in dataLst) {
            if (time < hsItem.startOffset + dayStartMs) {
                return hsItem
            }
        }
        return null
    }

    // xview 动画
    private fun playXViewAnim(){

        xView.state = XView.State.DakaIng

        // 来个动画
        val anim = ValueAnimator.ofFloat(xView.imgHeight.toFloat(), 0f)
        anim.duration = 2000
        anim.addUpdateListener {
            val value = it.animatedValue as Float
            xView.drawHeight = value
            xView.invalidate()

            if (it.animatedFraction >= 1.0f){
                xView.state = XView.State.AlreadyDaKa
                xView.invalidate()
            }
        }

        anim.start()
    }

    override fun isDarkMode() = false
}